Component({
  data: {
    selected: 0,
    color: "#999999",
    selectedColor: "#FFE736",
    list: [
      {
        pagePath: "/pages/home/index",
        text: "订单",
        icon: "📋"
      },
      {
        pagePath: "/pages/order/index", 
        text: "配送",
        icon: "🚚"
      },
      {
        pagePath: "/pages/message/index",
        text: "消息", 
        icon: "💬"
      },
      {
        pagePath: "/pages/profile/index",
        text: "我的",
        icon: "👤"
      }
    ]
  },
  
  attached() {
    // 获取当前页面路径，设置选中状态
    try {
      const pages = getCurrentPages();
      if (pages && pages.length > 0) {
        const currentPage = pages[pages.length - 1];
        if (currentPage && currentPage.route) {
          const currentPath = '/' + currentPage.route;
          const selected = this.data.list.findIndex(item => item.pagePath === currentPath);
          this.setData({
            selected: selected !== -1 ? selected : 0
          });
        } else {
          // 如果无法获取当前页面，默认选中第一个
          this.setData({ selected: 0 });
        }
      } else {
        // 如果页面栈为空，默认选中第一个
        this.setData({ selected: 0 });
      }
    } catch (error) {
      console.error('TabBar attached error:', error);
      // 出错时默认选中第一个
      this.setData({ selected: 0 });
    }
  },

  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset;
      const url = data.path;
      const index = data.index;
      
      this.setData({
        selected: index
      });
      
      wx.switchTab({
        url
      });
    }
  }
});
